package org.example.nettydemo.netty.udp;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Scanner;

/**
 * @author liujing
 */
public class UdpServerHandler extends ChannelInboundHandlerAdapter {
    private static final Logger logger = LoggerFactory.getLogger(UdpServerHandler.class);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 强制转换为 DatagramPacket
        DatagramPacket packet = (DatagramPacket) msg;

        // 提取消息内容（ByteBuf）
        ByteBuf byteBuf = packet.content();
        byte[] body=new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(body);
        System.out.println(new String(body));

//        System.out.println(Runtime.getRuntime().availableProcessors());
//        byte[] responseBytes = "hi,客户端,我是服务端".getBytes();
//        ctx.channel().writeAndFlush(Unpooled.wrappedBuffer(responseBytes));

//        logger.debug("线程启动");
        System.out.println("线程启动");
        // 启动一个线程处理用户输入
        new Thread(() -> {
            try (Scanner scanner = new Scanner(System.in)) {
                while (true) {
                    System.out.print("Enter response (type 'break' to exit): ");
                    String line = scanner.nextLine();
                    Channel channel = ctx.channel();
                    if ("break".equalsIgnoreCase(line)) {
                        channel.close();
                        break;
                    }
                    byte[] responseBytes = line.getBytes(CharsetUtil.UTF_8);
                    DatagramPacket responsePacket = new DatagramPacket(
                            Unpooled.wrappedBuffer(responseBytes),
                            packet.sender()
                    );
                    channel.writeAndFlush(responsePacket);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
//        logger.debug("结束");
        System.out.println("结束");

    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
    }
}
